#!/usr/bin/env python3

import udp
import threading
import sys
import os
import packet
import spwd
import crypt

def sendErr(sd, code, addr):
    return packet.send(sd, {'code': code}, addr, packet.ERROR)

def checkConnData(data):
    if (data == None
            or 'user' not in data
            or 'pwd' not in data
            or 'path' not in data):
        return 3

    #必须对python3解析器加特权位或者使用sudo运行
    try:
        sp = spwd.getspnam(data['user'])
    except Exception as e:
        return 0

    if crypt.crypt(data['pwd'], sp.sp_pwdp) != sp.sp_pwdp:
        return 1

    try:
        fp = open(data['path'], "rb")
    except Exception as e:
        return 2

    return fp

def run(sd, conn, srv):
    addr = conn[1]
    data = packet.get(conn[0], packet.CONNECT)

    fp = checkConnData(data)
    if type(fp) == int:
        return sendErr(sd, fp, addr)

    size = os.path.getsize(data['path'])

    if not packet.send(sd, {'size': size}, addr, packet.CONNECT_ACK):
        return None

    while True:
        data = {}
        data['data'] = fp.read(512)
        if (not packet.send(sd, data, addr, packet.DATA)
                or not packet.recv(sd, packet.DATA_ACK, 3.0)):
            return None

        if len(data['data']) != 512:
            break

    packet.send(sd, None, addr, packet.SHUTDOWN)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("请指定服务器操作(start|stop|restart)")
    else:
        udp.srv_daemon(9000, run, sys.argv[1])
